<template>
  <div class="app-container">
    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          v-hasPerm="['sys:menu:add']"
          type="success"
          icon="plus"
          @click="handleOpenDialog('0')"
        >
          {{ $t("common.add") }}
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="menuTableData"
        highlight-current-row
        row-key="id"
        :expand-row-keys="['1']"
        :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
        }"
        @row-click="handleRowClick"
      >
        <el-table-column :label="$t('menu.name')" min-width="200">
          <template #default="scope">
            <template v-if="scope.row.icon && scope.row.icon.startsWith('el-icon')">
              <el-icon style="vertical-align: -0.15em">
                <component :is="scope.row.icon.replace('el-icon-', '')" />
              </el-icon>
            </template>
            <template v-else-if="scope.row.icon">
              <svg-icon :icon-class="scope.row.icon" />
            </template>
            {{ scope.row.name }}
          </template>
        </el-table-column>

        <el-table-column :label="$t('menu.type')" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.type === MenuTypeEnum.CATALOG" type="warning">
              {{ $t("menu.menuType.1") }}
            </el-tag>
            <el-tag v-if="scope.row.type === MenuTypeEnum.MENU" type="success">
              {{ $t("menu.menuType.2") }}
            </el-tag>
            <el-tag v-if="scope.row.type === MenuTypeEnum.BUTTON" type="danger">
              {{ $t("menu.menuType.3") }}
            </el-tag>
            <el-tag v-if="scope.row.type === MenuTypeEnum.EXTLINK" type="info">
              {{ $t("menu.menuType.4") }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('menu.name')" align="left" width="150" prop="routeName" />
        <el-table-column :label="$t('menu.routePath')" align="left" width="150" prop="routePath" />
        <el-table-column :label="$t('menu.compPath')" align="left" width="250" prop="component" />
        <el-table-column :label="$t('menu.permUrl')" align="center" width="200" prop="permUrl" />
        <el-table-column :label="$t('menu.permission')" align="center" width="200" prop="perm" />
        <el-table-column :label="$t('common.showStatus')" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.visible === 1" type="success">{{ $t("common.show") }}</el-tag>
            <el-tag v-else type="info">{{ $t("common.hide") }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.sort')" align="center" width="80" prop="sort" />
        <el-table-column fixed="right" align="center" :label="$t('common.action')" width="220">
          <template #default="scope">
            <el-button
              v-if="scope.row.type == 'CATALOG' || scope.row.type == 'MENU'"
              v-hasPerm="['sys:menu:add']"
              type="primary"
              link
              size="small"
              icon="plus"
              @click.stop="handleOpenDialog(scope.row.id)"
            >
              {{ $t("common.add") }}
            </el-button>
            <el-button
              v-hasPerm="['sys:menu:edit']"
              type="primary"
              link
              size="small"
              icon="edit"
              @click.stop="handleOpenDialog(undefined, scope.row.id)"
            >
              {{ $t("common.edit") }}
            </el-button>
            <el-button
              v-hasPerm="['sys:menu:delete']"
              type="danger"
              link
              size="small"
              icon="delete"
              @click.stop="handleDelete(scope.row.id)"
            >
              {{ $t("common.delete") }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-drawer v-model="dialog.visible" :title="dialog.title" size="50%" @close="handleCloseDialog">
      <el-form ref="menuFormRef" :model="formData" :rules="rules">
        <el-form-item :label="$t('common.choose') + $t('menu.parentMenu0')" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            :placeholder="$t('menu.parentMenu')"
            :data="menuOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item :label="$t('menu.name')" prop="name">
          <el-input
            v-model="formData.name"
            :placeholder="$t('common.plsInput') + $t('menu.name')"
          />
        </el-form-item>

        <el-form-item :label="$t('menu.type')" prop="type">
          <el-radio-group v-model="formData.type" @change="handleMenuTypeChange">
            <el-radio value="CATALOG">{{ $t("menu.menuType.1") }}</el-radio>
            <el-radio value="MENU">{{ $t("menu.menuType.2") }}</el-radio>
            <el-radio value="BUTTON">{{ $t("menu.menuType.3") }}</el-radio>
            <el-radio value="EXTLINK">{{ $t("menu.menuType.4") }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="formData.type == 'EXTLINK'" :label="$t('menu.extUrl')" prop="path">
          <el-input v-model="formData.routePath" :placeholder="$t('menu.tip3')" />
        </el-form-item>

        <el-form-item v-if="formData.type == MenuTypeEnum.MENU" prop="routeName">
          <template #label>
            <div class="flex-y-center">
              {{ $t("menu.routeName") }}
              <el-tooltip placement="bottom" effect="light">
                <template #content>
                  {{ $t("menu.tip2") }}
                </template>
                <el-icon class="ml-1 cursor-pointer">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
          <el-input v-model="formData.routeName" placeholder="User" />
        </el-form-item>

        <el-form-item
          v-if="formData.type == MenuTypeEnum.CATALOG || formData.type == MenuTypeEnum.MENU"
          prop="routePath"
        >
          <template #label>
            <div class="flex-y-center">
              {{ $t("menu.routePath") }}
              <el-tooltip placement="bottom" effect="light">
                <template #content>
                  {{ $t("menu.tip0") }}
                </template>
                <el-icon class="ml-1 cursor-pointer">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
          <el-input
            v-if="formData.type == MenuTypeEnum.CATALOG"
            v-model="formData.routePath"
            placeholder="system"
          />
          <el-input v-else v-model="formData.routePath" placeholder="user" />
        </el-form-item>

        <el-form-item v-if="formData.type == MenuTypeEnum.MENU" prop="component">
          <template #label>
            <div class="flex-y-center">
              {{ $t("menu.compPath") }}
              <el-tooltip placement="bottom" effect="light">
                <template #content>{{ $t("menu.tip1") }}</template>
                <el-icon class="ml-1 cursor-pointer">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </div>
          </template>

          <el-input v-model="formData.component" placeholder="system/user/index" style="width: 95%">
            <template v-if="formData.type == MenuTypeEnum.MENU" #prepend>src/views/</template>
            <template v-if="formData.type == MenuTypeEnum.MENU" #append>.vue</template>
          </el-input>
        </el-form-item>

        <el-form-item
          v-if="formData.type !== MenuTypeEnum.BUTTON"
          prop="visible"
          :label="$t('common.showStatus')"
        >
          <el-radio-group v-model="formData.visible">
            <el-radio :value="1">{{ $t("common.show") }}</el-radio>
            <el-radio :value="0">{{ $t("common.hide") }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item :label="$t('common.sort')" prop="sort">
          <el-input-number
            v-model="formData.sort"
            style="width: 100px"
            controls-position="right"
            :min="0"
          />
        </el-form-item>

        <el-form-item :label="$t('menu.permUrl')" prop="permUrl">
          <el-input v-model="formData.permUrl" type="textarea" placeholder="system/role/add" />
        </el-form-item>

        <el-form-item
          v-if="formData.type == MenuTypeEnum.BUTTON"
          :label="$t('menu.permission')"
          prop="perm"
        >
          <el-input v-model="formData.perm" placeholder="sys:user:add" />
        </el-form-item>

        <el-form-item
          v-if="formData.type !== MenuTypeEnum.BUTTON"
          :label="$t('menu.icon')"
          prop="icon"
        >
          <icon-select v-model="formData.icon" :placehoder="$t('menu.iconPlaceholder')" />
        </el-form-item>

        <el-form-item
          v-if="formData.type == MenuTypeEnum.CATALOG"
          :label="$t('menu.redirectRoute')"
        >
          <el-input v-model="formData.redirect" :placeholder="$t('menu.redirectRoute')" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">{{ $t("common.confirm") }}</el-button>
          <el-button @click="handleCloseDialog">{{ $t("common.cancel") }}</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
const { t } = useI18n();
defineOptions({
  name: "SysMenu",
  inheritAttrs: false,
});

import MenuAPI, { MenuQuery, MenuForm, MenuVO } from "@/api/system/menu";
import { MenuTypeEnum } from "@/enums/MenuTypeEnum";

const queryFormRef = ref(ElForm);
const menuFormRef = ref(ElForm);

const loading = ref(false);
const dialog = reactive({
  title: t("common.add"),
  visible: false,
});

const queryParams = reactive<MenuQuery>({});
const menuTableData = ref<MenuVO[]>([]);
const menuOptions = ref<OptionType[]>([]);
const initialMenuFormData = ref<MenuForm>({
  id: undefined,
  parentId: "0",
  visible: 1,
  sort: 1,
  type: MenuTypeEnum.MENU,
  alwaysShow: 1,
  keepAlive: 0,
  permUrl: "",
  params: [],
});

const formData = ref({ ...initialMenuFormData.value });

const rules = reactive({
  parentId: [{ required: true, message: t("common.choose") + t("menu.topMenu"), trigger: "blur" }],
  name: [{ required: true, message: t("common.plsInput") + t("menu.name"), trigger: "blur" }],
  type: [{ required: true, message: t("common.choose") + t("menu.type"), trigger: "blur" }],
  routeName: [
    { required: true, message: t("common.plsInput") + t("menu.routeName"), trigger: "blur" },
  ],
  routePath: [
    { required: true, message: t("common.plsInput") + t("menu.routePath"), trigger: "blur" },
  ],
  component: [
    { required: true, message: t("common.plsInput") + t("menu.compPath"), trigger: "blur" },
  ],
  visible: [
    { required: true, message: t("common.plsInput") + t("menu.routePath"), trigger: "blur" },
  ],
});

const selectedMenuId = ref<string | undefined>();

function handleQuery() {
  loading.value = true;
  MenuAPI.getList(queryParams)
    .then((data) => {
      menuTableData.value = data;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

function handleRowClick(row: MenuVO) {
  selectedMenuId.value = row.id;
}

function handleOpenDialog(parentId?: string, menuId?: string) {
  if (!menuId) {
    formData.value = {
      id: undefined,
      parentId: "0",
      visible: 1,
      sort: 1,
      type: MenuTypeEnum.MENU,
      alwaysShow: 1,
      keepAlive: 0,
      permUrl: "",
      params: [],
    };
  }
  MenuAPI.getOptions(true)
    .then((data) => {
      menuOptions.value = [{ value: "0", label: t("menu.topMenu"), children: data }];
    })
    .then(() => {
      dialog.visible = true;
      if (menuId) {
        dialog.title = t("common.edit");
        MenuAPI.getFormData(menuId).then((data) => {
          initialMenuFormData.value = { ...data };
          formData.value = data;
        });
      } else {
        dialog.title = t("common.add");
        formData.value.parentId = parentId;
      }
    })
    .catch((err) => {
      console.error(err);
    });
}

function handleMenuTypeChange() {
  if (formData.value.type !== initialMenuFormData.value.type) {
    if (formData.value.type === MenuTypeEnum.MENU) {
      if (initialMenuFormData.value.type === MenuTypeEnum.CATALOG) {
        formData.value.component = "";
      } else {
        formData.value.routePath = initialMenuFormData.value.routePath;
        formData.value.component = initialMenuFormData.value.component;
      }
    }
  }
}

function handleSubmit() {
  menuFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      const menuId = formData.value.id;
      if (menuId) {
        MenuAPI.update(menuId, formData.value).then((res) => {
          if (res.data.code == 200) {
            ElMessage.success(res.data.message);
            handleCloseDialog();
            handleQuery();
          } else {
            ElMessage.error(res.data.message);
          }
        });
      } else {
        MenuAPI.add(formData.value).then((res) => {
          if (res.data.code == 200) {
            ElMessage.success(res.data.message);
            handleCloseDialog();
            handleQuery();
          } else {
            ElMessage.error(res.data.message);
          }
        });
      }
    }
  });
}

function handleDelete(menuId: number) {
  if (!menuId) {
    ElMessage.warning(t("common.plsChooseDeleteItem"));
    return false;
  }

  ElMessageBox.confirm(t("common.confirmDelete"), t("common.warning"), {
    confirmButtonText: t("common.confirm"),
    cancelButtonText: t("common.cancel"),
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      MenuAPI.deleteById(menuId)
        .then((res) => {
          if (res.data.code == 200) {
            ElMessage.success(res.data.message);
            handleQuery();
          } else {
            ElMessage.error(res.data.message);
          }
        })
        .finally(() => {
          loading.value = false;
        });
    },
    () => {
      ElMessage.info(t("common.cancelDelete"));
    }
  );
}

function resetRorm() {
  menuFormRef.value.resetFields();
  menuFormRef.value.clearValidate();
  formData.value = { ...initialMenuFormData.value };
}

function handleCloseDialog() {
  dialog.visible = false;
  resetRorm();
}

onMounted(() => {
  handleQuery();
});
</script>
